package cn.summit.core.authentication.kaptcha;

import cn.summit.core.authentication.handler.CustomfailureHandler;
import cn.summit.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 图形验证码验证
 *
 * @author summit
 * @since 2020/3/4 13:38
 */
@Component("kaotchaImageFilter")
@Slf4j
public class KaotchaImageFilter extends OncePerRequestFilter {

    @Autowired
    private SecurityProperties securityProperties;

    @Autowired
    private CustomfailureHandler customfailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

        // 1. 如果是post方式 的登录请求，则校验输入的验证码是否正确
        if (securityProperties.getAuthentication().getLoginProcessingUrl()
            .equals(request.getRequestURI()) && request.getMethod().equalsIgnoreCase("post")) {
            log.debug("进入图形验证码检查,当前url[{}]", request.getRequestURI());
            try {
                // 校验验证码合法性
                validate(request);
            } catch (AuthenticationException e) {
                // 交给失败处理器进行处理异常
                customfailureHandler.onAuthenticationFailure(request, response, e);
                // 一定要记得结束
                return;
            }
        }

        // 放行请求
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) {
        // 先获取seesion中的验证码
        String sessionCode = (String) request.getSession().getAttribute("SESSION_KEY");
        // 获取用户输入的验证码
        String inpuCode = request.getParameter("code");
        // 判断是否正确 todo
        // if (StringUtils.isBlank(inpuCode)) {
        //     throw new CustomValidException("验证码不能为空");
        // }
        // if (!inpuCode.equalsIgnoreCase(sessionCode)) {
        //     throw new CustomValidException("验证码输入错误");
        // }
    }
}
